using System;
using System.Collections;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Web.UI.Design;
using System.Web.UI.Design.WebControls;

namespace PickGold.Charting.Design
{
	internal class SeriesDataFieldXConvertor : DataFieldConverter
	{
		internal SeriesDataFieldXConvertor()
		{
		}

		private static IComponent GetComponent(ITypeDescriptorContext context)
		{
			return ConverterHelper.GetChartFromContext(context);
		}

		public override TypeConverter.StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
		{
			return this.GetStandardValuesInternal(GetComponent(context));
		}

		private TypeConverter.StandardValuesCollection GetStandardValuesInternal(IComponent component)
		{
			object[] values = null;
			if (component == null)
				return new TypeConverter.StandardValuesCollection(values);

			var site = component.Site;
			if (site == null)
				return new TypeConverter.StandardValuesCollection(values);

			var service = site.GetService(typeof(IDesignerHost)) as IDesignerHost;
			if (service == null)
				return new TypeConverter.StandardValuesCollection(values);

			var designer = service.GetDesigner(component) as DataBoundControlDesigner;
			if (designer != null)
			{
				var designerView = designer.DesignerView;
				if (designerView != null)
				{
					IDataSourceViewSchema schema = null;
					try
					{
						schema = designerView.Schema;
					}
					finally
					{
						if (schema != null)
						{
							var fields = schema.GetFields();
							if (fields != null)
							{
								var list = new ArrayList();
								foreach (var schema2 in fields)
								{
									if (this.IsApplicable(schema2))
										list.Add(schema2.Name);
								}
								values = list.ToArray();
							}
						}
					}
				}
			}
			if (values == null && designer != null && designer != null)
			{
				IDataSourceProvider provider = designer;
				IEnumerable dataSource = null;
				if (provider != null)
					dataSource = provider.GetResolvedSelectedDataSource();
				if (dataSource != null)
				{
					var dataFields = DesignTimeData.GetDataFields(dataSource);
					if (dataFields != null)
					{
						var list2 = new ArrayList();
						foreach (PropertyDescriptor descriptor in dataFields)
						{
							if (this.IsApplicable(descriptor))
								list2.Add(descriptor.Name);
						}
						values = list2.ToArray();
					}
				}
			}

			return new TypeConverter.StandardValuesCollection(values);
		}

		public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
		{
			return (GetComponent(context) != null);
		}

		protected virtual bool IsApplicable(PropertyDescriptor descriptor)
		{
			return true;
		}

		protected virtual bool IsApplicable(IDataSourceFieldSchema shema)
		{
			return true;
		}
	}
}
